package com.gxa.servlet.activity;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxa.pojo.Result;
import com.gxa.pojo.activity.Activity;
import com.gxa.pojo.activity.Activitys;
import com.gxa.pojo.activity.GoodsActivity;
import com.gxa.pojo.goods.Goods;
import com.gxa.service.avticity.ActivityService;
import com.gxa.service.avticity.impl.ActivityServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(urlPatterns = "/addActivityGoods")
public class AddActivityGoodsServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        ActivityService activityService = new ActivityServiceImpl();
        int aid = Integer.parseInt(request.getParameter("aid"));


        BufferedReader streamReader = new BufferedReader( new InputStreamReader(request.getInputStream(),"UTF-8"));
        StringBuilder json = new StringBuilder();
        String inputStr;
        while ((inputStr = streamReader.readLine()) != null) {
            json.append(inputStr);
        }
        String jsonString = json.toString();
        List<Goods> goodsList = JSON.parseArray(jsonString,Goods.class);
        GoodsActivity goodsActivity = new GoodsActivity();
        boolean b= false;
        goodsActivity.setAid(aid);
        for (int i = 0; i < goodsList.size(); i++) {
            goodsActivity.setCount(goodsList.get(i).getCount());
            goodsActivity.setGid(goodsList.get(i).getGid());
            b = activityService.addActivityGoods(goodsActivity);
        }

        PrintWriter writer = response.getWriter();
        Map<String,Object> map = new HashMap<>();
        String s = null;
        if (b){
            map.put("result", Result.ok("success"));
            s= objectMapper.writeValueAsString(map);

        }else {
            map.put("result",Result.error());
            s= objectMapper.writeValueAsString(map);
        }
        writer.write(s);
        writer.flush();
        writer.close();
        streamReader.close();
    }
}
